package com.hdu.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hdu.entity.Class;
import com.hdu.entity.Exam;
import com.hdu.mapper.CaseMapper;
import com.hdu.pojo.Grade;
import com.hdu.pojo.PageBean;
import com.hdu.service.CaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CaseServiceImpl implements CaseService {

    private final CaseMapper caseMapper;

    /**
     * 获取学生信息
     */
    @Override
    public PageBean<Grade> page(Integer page, Integer pageSize, String id, String username, String prop, String order, String tID) {

        String cID = Db.lambdaQuery(Class.class).eq(Class::getTID, tID).one().getCID();

        //1. 设置分页参数
        PageHelper.startPage(page, pageSize);

        List<Grade> gradeList = caseMapper.averageStudent(id, username, prop, order, cID);

        Page<Grade> p = (Page<Grade>) gradeList;

        //3. 封装PageBean对象
        return new PageBean<>(p.getTotal(), p.getResult());
    }

    /**
     * 获取班级平均分
     */
    @Override
    public List<Double> averageClass(String tID) {
        String cID = Db.lambdaQuery(Class.class).eq(Class::getTID, tID).one().getCID();
        String[] grade = caseMapper.averageClass(cID).toString().split(",");
        Double[] gradeList = new Double[grade.length];
        for (int i = 0; i < grade.length; i++) {
            gradeList[i] = Double.parseDouble(grade[i]);
            gradeList[i] = i < 3 ? (int) (gradeList[i] / 1.5) : gradeList[i];
        }
        return Arrays.asList(gradeList);
    }

    /**
     * 获取班级近期单科成绩
     */
    @Override
    public List<Integer> limitStudent(String sID, String subject) {
        return caseMapper.limitStudent(sID, subject);
    }

    /**
     * 获取班级近期单科成绩
     */
    @Override
    public List<Exam> limitSubject(String tID) {

        String cID = Db.lambdaQuery(Class.class).eq(Class::getTID, tID).one().getCID();
        List<Exam> examList = caseMapper.examLimit();
        for (Exam exam : examList) {
            Grade grade = caseMapper.averageSubject(cID, exam.getEID());
            exam.setGrade(grade);
        }
        Collections.reverse(examList);
        return examList;
    }
}

